import nProgress from 'nprogress'//进度条插件
import router from './router'
import store from './store'
import { asyncRoutes } from '@/router'

/* 设置路由白名单 */
const whiteList = ['/login', '/404']
/* 通过路由守卫控制页面的跳转 */
router.beforeEach(async (to, from, next) => {
  nProgress.start()//浏览器进度条插件
  if (store.getters.token) {
    //有token的情况下
    //to.path === '/login' ? next('/') : next()
    if (to.path === '/login') {
      next('/')
      nProgress.done()
    } else {
      /* 判断是否获取过用户数据 */
      if (!store.getters.userId) {
        let { roles } = await store.dispatch('user/getUserInfo')
        //roles.menus 获取到的用户权限
        //asyncRoutes 动态路由
        let filterRoutes = asyncRoutes.filter(item => {
          //return true/false
          //判断当前用户是否有该路由的权限
          return roles.menus.includes(item.name)
        })
        console.log(filterRoutes);
      }
      next()
    }
    //next('/')有地址的情况下不会执行后置守卫，需要手动关闭进度条
  } else {
    //没有token的情况下
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
      nProgress.done()
    }
  }


})
router.afterEach((to, from, next) => {
  nProgress.done()
})